<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" placeholder="请输入关键字" style="width: 200px;" class="filter-item" size="mini" round @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.wikiCropTypeId" placeholder="所属分类" clearable style="width: 120px;margin-left: 10px" class="filter-item" size="mini" round @change="handleFilter">
        <el-option v-for="item in cropoption" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" size="mini" style="margin-left: 10px;" round @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px; float:right" round size="mini" @click="delData">
        删除
      </el-button>
    </div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      stripe
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @selection-change="selectRow"
    >
      <el-table-column type="selection" width="77" />
      <el-table-column label="序号" align="center" width="80">
        <template slot-scope="{$index}">
          <span>{{ $index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="病虫害名称" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.diseaseInsectName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="病虫害别名" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.diseaseInsectAlias }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.wikiCropTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" min-width="90px">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布人" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createUser }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="text" size="medium" title="详情" @click="handlesee(row)"><i class="el-icon-tickets" />
          </el-button>
          <el-button type="text" size="medium" title="编辑" @click="handleUpdate(row)"><i class="el-icon-edit" />
          </el-button>
          <el-button size="medium" type="text" title="删除" @click="handleDelete(row)"><i class="el-icon-delete" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="25%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width:300px;" size="mini">
        <el-form-item label="病虫害名称" prop="diseaseInsectName">
          <el-input v-model="temp.diseaseInsectName" placeholder="请输入病虫害名称" />
        </el-form-item>
        <el-form-item label="病虫害别名" prop="diseaseInsectAlias">
          <el-input v-model="temp.diseaseInsectAlias" placeholder="请输入病虫害别名" />
        </el-form-item>
        <el-form-item label="病虫害标示" prop="diseaseInsectLabel">
          <el-input v-model="temp.diseaseInsectLabel" placeholder="请输入病虫害唯一标示" />
        </el-form-item>
        <el-form-item label="选择分类" prop="type">
           <el-select v-if="isNeedAudits" v-model="temp.wikiCategoryId" placeholder="请选择" clearable style="width: 120px" class="filter-item" >
        <el-option v-for="item in categoryoption" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
       <el-select v-model="temp.wikiCropTypeId" placeholder="请选择" clearable style="width: 120px" class="filter-item" >
        <el-option v-for="item in cropoption" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
        </el-form-item>
        <el-form-item label="添加图片" prop="pictureUrls">
            <el-upload
              ref="upload"
              class="upload-demo"
              action="1"
              :auto-upload="false"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleAvatarChange"
              :file-list="temp.files"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <img
                v-if="this.imageUrl"
                :src="this.imageUrl"
                class="avatar"
              /> -->
          </el-upload>
        </el-form-item>
        <el-form-item label="病虫害简介" prop="diseaseInsectIntroduction">
          <el-input v-model="temp.diseaseInsectIntroduction" placeholder="请输入病虫害简介，不超过300字" />
        </el-form-item>
        <el-form-item label="植物症状" prop="studentId">
          <el-input v-model="temp.plantSymptom" placeholder="请输入植物症状，不超过800字" />
        </el-form-item>
        <el-form-item label="形态特征" prop="studentId">
          <el-input v-model="temp.morphologyFeature" placeholder="请输入形态特征，不超过800字" />
        </el-form-item>
        <el-form-item label="生活习性" prop="studentId">
          <el-input v-model="temp.livingHabit" placeholder="请输入生活习性，不超过800字" />
        </el-form-item>
        <el-form-item label="传播途径" prop="studentId">
          <el-input v-model="temp.propagationPath" placeholder="请输入传播途径，不超过800字" />
        </el-form-item>
        <el-form-item label="发生规律" prop="studentId">
          <el-input v-model="temp.occurrenceRegularity" placeholder="请输入发生规律，不超过800字" />
        </el-form-item>
        <el-form-item label="农业防治" prop="studentId">
          <el-input v-model="temp.agricultureControl" placeholder="请输入农业防治，不超过800字" />
        </el-form-item>
        <el-form-item label="化学防治" prop="studentId">
          <el-input v-model="temp.chemistryControl" placeholder="请输入化学防治，不超过800字" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          v-if="isNeedAudit"
          type="primary"
          size="mini"
          @click="dialogStatus==='create'?createData():updateData()"
        >
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getInsectList,addInsectList,deleteInsectList,deleteInsectLists,updateInsectList,getlistbyId  } from '@/api/Insect'
import{getallbotanyTypeList}from'@/api/botanyType'
import{getInsectTypeList}from'@/api/InsectType'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { isPhone, isName, isStunum } from '@/utils/validate'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isNeedAudit:true,
      isNeedAudits:true,
      deleteImage:[],
      sels:[],
      tableKey: 0,
      list:[],
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: '',
        wikiCropTypeId: '',
        page: 1,
        limit: 20
      },
      cropoption: [],
      categoryoption: [],
      temp: {
        item: [],
        diseaseInsectName: '', //
        diseaseInsectId: '',
        diseaseInsectAlias: '',
        wikiCropTypeName: '',
        createTime: '',
        createUser: '',
        agricultureControl: '',
        chemistryControl: '',
        diseaseInsectIntroduction: '',
        diseaseInsectLabel: '', //
        files: [],
        livingHabit: '',
        morphologyFeature: '',
        occurrenceRegularity: '',
        plantSymptom: '',
        propagationPath: '',
        wikiCategoryId: '', //
        wikiCropTypeId: ''//
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改基本信息',
        create: '新建基本信息',
        see: '查看基本信息'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    getallbotanyTypeList().then(res => {
      console.log(res.data[0])
      for (let i = 0; i < res.data.length; i++) {
        this.cropoption.push({ value: `${res.data[i].wikiCropTypeId}`, label: `${res.data[i].wikiCropTypeName}` })
      }
    })
    getInsectTypeList(this.listQuery).then(res => {
      for (let i = 0; i < res.data.length; i++) {
        this.categoryoption.push({ value: `${res.data[i].wikiCategoryId}`, label: `${res.data[i].wikiCategoryName}` })
      }
    })
  },
  methods: {
    handleRemove(file,fileList) {
      if (this.dialogStatus == 'update') {
        this.deleteImage.push(file.pictureId)
        console.log(this.deleteImage)
      }
    },
    handlePreview(file) {
      console.log(file)
    },
    handleAvatarChange(file, fileList) {
      this.temp.files = fileList
    },
    getList() {
      this.listLoading = true
      getInsectList(this.listQuery).then(res => {
        this.list = res.data
        // this.total = res.data.total;
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1

      this.getList()
    },

    resetTemp() {
      this.temp = {
        ids:[],
       item:[],
        diseaseInsectName:'',//
        diseaseInsectId:'',
        diseaseInsectAlias:'',
        wikiCropTypeName:'',
        createTime:'',
        createUser:'',
        agricultureControl:'',
        chemistryControl:'',
        diseaseInsectIntroduction:'',
        diseaseInsectLabel:'',//
        files:[],
        livingHabit:'',
        morphologyFeature:'',
        occurrenceRegularity:'',
        plantSymptom:'',
        propagationPath:'',
        wikiCategoryId:'',//
        wikiCropTypeId:'',//
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.isNeedAudit = true
      this.isNeedAudits = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          var createMeasureData = new FormData()
          createMeasureData.append('wikiCategoryId', this.temp.wikiCategoryId)
           createMeasureData.append('wikiCropTypeId', this.temp.wikiCropTypeId)
            createMeasureData.append('diseaseInsectName', this.temp.diseaseInsectName)
            createMeasureData.append('diseaseInsectLabel', this.temp.diseaseInsectLabel)
            createMeasureData.append('diseaseInsectIntroduction', this.temp.diseaseInsectIntroduction)
            createMeasureData.append('plantSymptom', this.temp.plantSymptom)
            createMeasureData.append('livingHabit', this.temp.livingHabit)
            createMeasureData.append('morphologyFeature', this.temp.morphologyFeature)
            createMeasureData.append('occurrenceRegularity', this.temp.occurrenceRegularity)
            createMeasureData.append('propagationPath', this.temp. propagationPath)
            createMeasureData.append('agricultureControl', this.temp.agricultureControl)
            createMeasureData.append('chemistryControl', this.temp.chemistryControl)
            createMeasureData.append('diseaseInsectAlias', this.temp.diseaseInsectAlias)
         
         for (let i = 0; i < this.temp.files.length; i++) {
        createMeasureData.append('files', this.temp.files[i].raw)
      }
      console.log(this.temp)
          addInsectList(createMeasureData).then(() => {
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
      this.dialogFormVisible = false
    },
   
    handlesee(row){
      getlistbyId(row).then(res=>{
        this.temp = res.data
        this.temp.wikiCropTypeId = res.data.wikiCropTypeName
        this.temp.files =[]
        //console.log(res.data)
         for (let i = 0; i < res.data.pictureUrls.length; i++) {
        this.temp.files.push({ 'url':res.data.pictureUrls[i].pictureUrl,
          'pictureId': res.data.pictureUrls[i].pictureId })
      }
       console.log(this.temp)
      })
      //this.temp.files = []
     
      this.dialogStatus = 'see'
      this.dialogFormVisible = true
      this.isNeedAudit = false
      this.isNeedAudits = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
    getlistbyId(row).then(res=>{
        this.temp = res.data
        //this.temp.ids = res.data.pictureUrls[0].pictureId
        this.temp.wikiCropTypeId = res.data.wikiCropTypeName
        this.temp.diseaseInsectId = row.diseaseInsectId
         this.temp.files =[]
         for (let i = 0; i < res.data.pictureUrls.length; i++) {
        this.temp.files.push({ 'url':res.data.pictureUrls[i].pictureUrl,
          'pictureId': res.data.pictureUrls[i].pictureId })
      }
        console.log(this.temp)
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.isNeedAudit = true
      this.isNeedAudits = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
           var createMeasureData = new FormData()
           createMeasureData.append('ids', this.deleteImage)
            createMeasureData.append('diseaseInsectId', this.temp.diseaseInsectId)
          createMeasureData.append('wikiCategoryId', this.temp.wikiCategoryId)
           createMeasureData.append('wikiCropTypeId', this.temp.wikiCropTypeId)
            createMeasureData.append('diseaseInsectName', this.temp.diseaseInsectName)
            createMeasureData.append('diseaseInsectLabel', this.temp.diseaseInsectLabel)
            createMeasureData.append('diseaseInsectIntroduction', this.temp.diseaseInsectIntroduction)
            createMeasureData.append('plantSymptom', this.temp.plantSymptom)
            createMeasureData.append('livingHabit', this.temp.livingHabit)
            createMeasureData.append('morphologyFeature', this.temp.morphologyFeature)
            createMeasureData.append('occurrenceRegularity', this.temp.occurrenceRegularity)
            createMeasureData.append('propagationPath', this.temp. propagationPath)
            createMeasureData.append('agricultureControl', this.temp.agricultureControl)
            createMeasureData.append('chemistryControl', this.temp.chemistryControl)
            createMeasureData.append('diseaseInsectAlias', this.temp.diseaseInsectAlias)
         for (let i = 0; i < this.temp.files.length; i++) {
        createMeasureData.append('files', this.temp.files[i].raw)
      }
          updateInsectList(createMeasureData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },

    // 删除
    handleDelete(row) {
      console.log(row)
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteInsectList(row)
        this.getList()
        this.$notify({
          title: 'Success',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    selectRow(sels) {
      this.sels = sels
      // console.log(sels.length)
    },
    // 批量删除
    delData() {
      this.$confirm(
        '确定要删除吗？删除后不能恢复',
        '系统提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        for (let i = 0; i < this.sels.length; i++) {
          this.temp.item[i] = this.sels[i].diseaseInsectId
        }
        deleteInsectLists(this.temp)
        this.getList()
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        // this.getList()
      })
    }

  }
}
</script>
